const webSocket = require('ws');

const server = new webSocket.Server({ //创建一个ws服务对象
    port: 3000,
    host: 'localhost'
});

let users = {};

let count = 0;
let arr= [];

server.on("connection", client => {

    client.id = ++count;

    users[client.id] = client;
    console.log(client.id);

    client.on("message", msg => {
        let obj = JSON.parse(msg);
        if(obj.username){
            arr.push(obj.username);
        }
        boardCaster(msg, client);
    });

    client.on('close', () => {
        console.log(`用户${client.id}下线了`);
        for (var key in users) {
            users[key].send(`${arr[client.id].toString()}`)
        }
        // boardCaster(`${client.id}`,client);
        delete users[client.id];
    })
});

function boardCaster(msg, client) {
    for (var key in users) {
        // users[key].send(`用户${client.id}说:${msg}`);
        users[key].send(`${msg}`);
        users[key].send(`${arr.toString()}`)
    }
}